package com.learnjava.learnjava1.jpa.specification;

import com.learnjava.learnjava1.jpa.entity.CompanyEntity;
import com.learnjava.learnjava1.jpa.entity.CompanyEntity_;
import org.springframework.data.jpa.domain.Specification;

import java.util.Optional;
import java.util.stream.Stream;

public class CompanySpecification {
    public static Specification<CompanyEntity> parseFilters(String title, Boolean active, Long id) {
        Optional<Specification<CompanyEntity>> spec = Stream.of(
                hasId(id),
                hasActive(active),
                hasTitle(title)
        ).reduce(Specification::allOf);
        return spec.orElse(null);
    }

    private static Specification<CompanyEntity> hasTitle(String title) {
        return (root, query, criteriaBuilder) -> {
            if (title == null || title.isEmpty()) {
                return null;
            }
            return criteriaBuilder.like(criteriaBuilder.lower(root.get(CompanyEntity_.TITLE)), "%" + title.toLowerCase() + "%");
        };
    }

    private static Specification<CompanyEntity> hasActive(Boolean active) {
        return (root, query, criteriaBuilder) -> {
            if (active == null) {
                return null;
            } else {
                return criteriaBuilder.equal(root.get(CompanyEntity_.IS_ACTIVE), Boolean.parseBoolean(String.valueOf(active)));
            }
        };
    }

    private static Specification<CompanyEntity> hasId(Long id) {
        return (root, query, criteriaBuilder) -> {
            if (id == null) {
                return null;
            } else {
                return criteriaBuilder.equal(root.get(CompanyEntity_.ID), id);
            }
        };
    }
}
